package com.blq.common.utils;

import cn.hutool.json.JSONObject;
import jodd.util.StringUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpClientUtil {
    /**
     * 默认连接超时时间
     */
    private final static int DEFAULT_CONNECTION_TIME_OUT = 3000;
    /**
     *
     */
    private final static int DEFAULT_SO_TIME_OUT = 10000;

    /***
     * 默认字符编码
     */
    private final static String DEFAULT_CHARSET_UTF_8 = "UTF-8";

    /**
     * Post 方式http请求
     *
     * @param urlvalue          url 如：http://www.51book.com/liantuo/manage/pay4Alipay.in
     * @param paras             参数
     * @param charset           字符编码 默认 utf-8
     * @param connectionTimeout 建立连接超时时间 默认3000毫秒
     * @param soTimeout         处理超时时间 默认10000毫秒
     * @return
     */
    public static String requestAsHttpPOST(String urlvalue,
                                           Map<String, String> paras, String charset, Integer connectionTimeout, Integer soTimeout) {
        HttpClient http = new HttpClient();
        HttpConnectionManagerParams managerParams = http.getHttpConnectionManager().getParams();
        if (connectionTimeout != null && connectionTimeout.intValue() != 0) {
            managerParams.setConnectionTimeout(connectionTimeout);
        } else {
            managerParams.setConnectionTimeout(DEFAULT_CONNECTION_TIME_OUT);
        }
        if (soTimeout != null && soTimeout.intValue() != 0) {
            managerParams.setSoTimeout(soTimeout);
        } else {
            managerParams.setSoTimeout(DEFAULT_SO_TIME_OUT);
        }
        PostMethod method = new PostMethod(urlvalue);
        if (StringUtil.isEmpty(charset)) {
            method.getParams().setHttpElementCharset(DEFAULT_CHARSET_UTF_8);
            method.getParams().setContentCharset(DEFAULT_CHARSET_UTF_8);
            method.getParams().setCredentialCharset(DEFAULT_CHARSET_UTF_8);
        } else {
            method.getParams().setHttpElementCharset(charset);
            method.getParams().setContentCharset(charset);
            method.getParams().setCredentialCharset(charset);
        }
        if (paras != null) {
            for (String key : paras.keySet()) {
                method.addParameter(key, paras.get(key));
            }
        }
        String result = "";
        try {
            http.executeMethod(method);
            result = method.getResponseBodyAsString();
        } catch (IOException e) {
            result = "";
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return result;
    }
     /**
      * @title doGet
      * @description 发送Get请求
      * @author Blq
      * @updateTime 2022/7/6 11:01
      * @throws
      */
    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String sendPostJson(String URL, JSONObject json, HashMap<String,String> headerMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            post.addHeader(next.getKey(),next.getValue());
        }
        String result;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            System.out.println(httpResponse.getEntity().toString());
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功，做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
